package com.youlai.boot.common.util;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * 分布式业务编号生成器
 */
public class DistributedBusinessNoGenerator {
    private static final DateTimeFormatter FORMATTER = DateTimeFormatter.ofPattern("yyyyMMddHHmmss");

    // 机器标识（可根据实际部署环境设置）
    private static final String MACHINE_ID = "01";

    private static final AtomicInteger SEQUENCE = new AtomicInteger(0);
    private static final int MAX_SEQUENCE = 9999;

    public static String generate(String flag) {
        String dateTime = LocalDateTime.now().format(FORMATTER);
        int sequence = SEQUENCE.getAndIncrement();

        if (sequence > MAX_SEQUENCE) {
            SEQUENCE.compareAndSet(sequence + 1, 0);
            sequence = SEQUENCE.getAndIncrement();
        }
        // 格式: 时间戳 + 机器ID + 序列号
        return dateTime + flag + MACHINE_ID + String.format("%04d", sequence);
    }

}
